#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'walkingsky tangxn_1@163.com'

import xlwt
import xlrd
from xlutils.copy import copy 
import os
import re

from datetime import date, datetime


def read_excel(file,row,sheet = 1):
    try:
        wb = xlrd.open_workbook(filename=file)  # 打开文件
        sheet1 = wb.sheet_by_index(sheet -1)  # 通过索引获取表格
        rows = sheet1.row_values(row )  # 获取行内容
    except:
        return False
    else:
        return rows


#设置表格样式
def set_style(name,height,bold=False):
	style = xlwt.XFStyle()
	font = xlwt.Font()
	font.name = name
	font.bold = bold
	font.color_index = 4
	font.height = height
	style.font = font
	return style

#写Excel
def write_excel(file,row,sheet = 1):
    file = re.sub(r'\.xlsx$','.xls',file,1)
    #print(file)
    if os.path.exists(file):
        wb = xlrd.open_workbook(filename=file)  # 打开文件
        sheet = sheet - 1
        rows = wb.sheets()[sheet].nrows
        excel = copy(wb) # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象
        table = excel.get_sheet(sheet) # 用xlwt对象的方法获得要操作的sheet
        row_num = rows
        colum = 0 
        for value in row:
            table.write(row_num, colum, value) # xlwt对象的写方法，参数分别是行、列、值 
            colum = colum + 1           
        excel.save(file) # xlwt对象的保存方法，这时便覆盖掉了原来的excel
    else:
        f = xlwt.Workbook()
        sheet1 = f.add_sheet('log',cell_overwrite_ok=True)
        #写最后一行
        for i in range(0,len(row)):
            sheet1.write(0,i,row[i],set_style('Times New Roman',220,True))
        f.save(file)
